package top.rushpeak.edu03.admin.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.log4j.Logger;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;


public class UploadFileUtil {

	private static final Logger LOG=Logger.getLogger(UploadFileUtil.class);
	static {
		PropKit.use("properties/config.properties");
	}
	public static void saveFile(UploadFile uploadFile, String fieldName,Record record) throws IOException {
		if (uploadFile != null) {
			String dest = UUIDUtil.getUUID() + ".jpg";
			InputStream in = new FileInputStream(uploadFile.getFile());
//			String date=DateUtil.dateFormat(new Date(), "yyyyMMdd");
			File pfile = new File(PropKit.get("imageUpload"));
			if(!pfile.exists()||!pfile.isDirectory()){
				pfile.mkdirs();
			}
			File file = new File(PropKit.get("imageUpload")+ dest);
			inputstreamToFile(in, file);
			record.set(fieldName, dest);
		}
	}

	public static void delFile(Record record){
		String imgUrl = record.getStr("image_url");
		File file = new File(PropKit.get("imageUpload")+ imgUrl);
		if(file.exists()&&file.isFile()){
			file.delete();
			LOG.info("UploadFileUtil.delFile删除"+imgUrl);
		}else{
			LOG.error("UploadFileUtil.delFile删除失败");
		}
	}
	
	public static void inputstreamToFile(InputStream ins, File file) throws IOException {
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
	}

	public static void delFiles(Record record) {
		for(int i=0;i<5;i++){			
			String imgUrl = record.getStr("cimg"+i);
			if(!"".equals(imgUrl)){
				delFileCom(imgUrl);
			}
		}
		
	}
	
	public static void delFileCom(String imgurl){
		if(!"".equals(imgurl)){
			File file = new File(PropKit.get("imageUpload")+ imgurl);
			if(file.exists()&&file.isFile()){
				file.delete();
				LOG.info("UploadFileUtil.delFile删除"+imgurl);
			}else{
				LOG.error("UploadFileUtil.delFile删除失败");
			}
		}
	}
	
}
